package com.tongtailian.www.stir.utils;

import android.text.TextUtils;
import android.util.Log;

import java.util.regex.Pattern;

/**
 * @author liuml
 * @explain
 * @time 2020/10/11 17:09
 */
public class CharUtils {

    /**
     * 根据Unicode编码判断中文汉字和中文符号
     *
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }


    /**
     * 合法的英文判断：
     *
     * @param c
     * @return
     */
    public static boolean isEnglishByREG(char c) {
        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
            return true;
        }
        return false;
    }

    /**
     * 根据正则表达式判断部分CJK字符（CJK统一汉字）
     *
     * @param str
     * @return
     */
    public static boolean isChineseByREG(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[\\u4e00-\\u9fa5_a-zA-Z0-9]+$");
        return pattern.matcher(str.trim()).find();
    }

    /**
     * 过滤掉非中英文
     *
     * @param str
     * @return
     */
    public static String getLetterAndChinese(String str) {
        Log.e("AddLinkmanActivity", "要判断的字符串是:" + str);
        char[] ch = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ch.length; i++)
            if (isChineseByREG("" + ch[i]) ||
                    isEnglishByREG(
                            ch[i]))
                sb.append("" + ch[i]);

        return sb.toString();
    }

    /**
     * 判断是否是中英文
     *
     * @param str
     * @return
     */
    public static boolean isLetterAndChinese(String str) {
        Log.e("AddLinkmanActivity", "要判断的字符串是:" + str);
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++)
            if (isChineseByREG("" + ch[i]) ||
                    isEnglishByREG(
                            ch[i]))
                return true;


        return false;
    }
}